<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册</title>
    <link rel="stylesheet" href="/css/common.css">
    <link rel="stylesheet" href="/css/login.css">
</head>
<body>
    <!-- 导航栏 -->
    <div class="nav">
        网页聊天
    </div>

    <!-- 主窗口 -->
    <div class="login-container">
        <div class="login-dialog">
            <h3>注册</h3>
            <div class="row">
                <span>用户名</span>
                <input type="text" id="username">
            </div>

            <div class="row">
                <span>密码</span>
                <input type="password" id="password">
            </div>
            <div class="row">
                <button id="submit">注册</button>
            </div>  
        </div>
    </div>

    <!-- 使用jquery实现表单提交 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
    <!-- 将前端数据发送到后端 -->
    <script>
        let submitButtom=document.querySelector("#submit");
        submitButtom.onclick=function(){
            //获取到输入框的信息
            let username=document.querySelector("#username").value;
            let password=document.querySelector("#password").value;
            
            if(username==''||password==''){
                alert("用户名或密码不能为空");
                return;
            }
            //发送登录请求
            $.ajax({
                url:"/register",
                type:"post",
                //data中，带引号的参数要与后端对应
                data:{
                    "username":username,
                    "password":password
                },
                success: function(body){
                    //处理相应,body为user对象，这里的判断逻辑是后端约定的，错误登录userId为0
                    if(body&&body.userId>0){
                        alert("登录成功");
                        //跳转到聊天页面
                        location.assign("/login.html");
                    } else{
                        alert("该用户名已被占用");
                    }

                }
            });
            
        }
    </script>
        
</body>
</html>